package me.helllp.dake.generator.engine.mybatis;

import freemarker.template.TemplateException;
import me.helllp.dake.generator.FreeMarkerUtil;
import me.helllp.dake.generator.engine.RdbmsGenerator;
import me.helllp.dake.generator.meta.ProjectMetaData;
import me.helllp.dake.generator.utils.FileAndPathUtils;
import me.helllp.dake.generator.utils.UnderlineToCamelUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * mybatis xml的配置文件生成
 */
public class XmlGenerator extends RdbmsGenerator {
    public XmlGenerator(ProjectMetaData projectMetaData) {
        super(projectMetaData);
    }

    @Override
    public void generator() throws IOException, TemplateException {
        // 创建resource下mapper目录
        File file = FileAndPathUtils.pathAppend(this.getProjectMetaData().getSrcResourcePath(), "mapper");
        FileAndPathUtils.makeDir(file);

        Map<String, Object> dataMap = new HashMap<>();

        getTables().stream().forEach(table -> {
            String name = UnderlineToCamelUtils.underlineToCamel(table.getTableName(), false) + "Mapper";
            dataMap.put("mapperName", this.getProjectMetaData().getBasePackage() + ".mapper." + name);

            try {
                FreeMarkerUtil.genSrc(FileAndPathUtils.pathAppend(file.getCanonicalPath(), name + ".xml") , "MyBatisMapper.ftl", dataMap);
            } catch (IOException | TemplateException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
